import router from '@/router'
import axios, { type Method } from 'axios'

const baseURL = 'http://localhost'
const instance = axios.create({
  baseURL,
  timeout: 3000
})

instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token && config.headers) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  err => Promise.reject(err)
)

instance.interceptors.response.use(
  res => {
    if (res.data?.message !== 'success') {
      if (res.data.code === 401) {
        localStorage.removeItem('token')
        router.push({
          path: '/login',
          query: { returnUrl: router.currentRoute.value.fullPath }
        })
      }
      Snackbar['error'](res.data.data)
      return Promise.reject(res)
    }
    return res.data.data
  },
  err => Promise.reject(err)
)

type Data<T> = {
  code: number
  message: string
  data: T
}

const request = <T>(
  url: string,
  method: Method = 'GET',
  submitData?: object
) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}

export { baseURL, instance }
export default request
